<?php

namespace App\Http\Controllers\Util;

use App\Model\Attachment;
use App\Server\UploadServer;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UploadController extends Controller
{
    public function upload(Request $request,UploadServer $uploadServer,Attachment $attachment){
//        dd(1);
        if($file = $request->file('file')){
            $path=$uploadServer->upload($file,$this->isImage($file)?'image':'file');
            auth()->user()->attachment()->create(['filename'=>$file->getClientOriginalName(),'path'=>url($path)]);
            return ['file'=>url($path),'code'=>0];

        }




    }
    public function isImage($file){
        //strtolower 扩展名不区分大小写
        $ext = strtolower ( $file->getClientOriginalExtension () );

        return in_array ( $ext , [ 'jpg' , 'jpeg' , 'png' , 'gif' ] );
    }
    public function lists(){
        $data = Attachment::where('user_id',auth ()->user ()->id)->paginate(2);
        $db = $data->toArray();

        foreach($db['data'] as $k=>$v){
            $db['data'][$k]['url'] = $v['path'];
        }
        //dd($db);
        return [
            'code'=>0,
            'data'=>$db['data'],
            'page'=>$data->links() . ''
        ];
    }
}
